/*
    Copyright (c) 2018 - 2023 jones
*/

import $ from 'jquery'
import HQChart from 'hqchart'
import { getTrKline } from '@/axios/api'

var HQData = {};

function randomNum1(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        default:
            return 0;
    }
}

// 清除定时器
function clearDing() {
    clearInterval(window.timer);
    window.timer = null;
}

// 初始化定时器
function initTimer(time, callback) {
    window.timer = setInterval(() => {
        let hqchartData = { ...initArr };
        let data = hqchartData.data;
        let lastItem = data[data.length - 1];
        let newItem = [...lastItem];
        newItem[0] = newItem[0] + time;
        newItem[2] = newItem[5];
        newItem[3] = newItem[5] * (1 + randomNum1(1, 9) / 1000);
        newItem[4] = newItem[5] * (1 - randomNum1(1, 9) / 1000);
        newItem[5] = newItem[5] * (1 + randomNum1(-5, 5) / 1000);
        newItem[6] = randomNum1(1000, 9999);
        newItem[7] = newItem[5] * newItem[6];
        data.push(newItem);
        callback(hqchartData);
    }, 5000);
}

var initArr = null;

HQData.Log = function (message) {
    console.log(message);
}

HQData.NetworkFilter = function (data, callback) {
  console.log("HQData::NetworkFilter,data.Name",data.Name);
    switch (data.Name) {
        case "MinuteChartContainer::RequestMinuteData":
            HQData.RequestMinuteData(data, callback);
            break;
        case "MinuteChartContainer::RequestHistoryMinuteData":
            HQData.RequestMinuteData(data, callback);
            break;

        case "KLineChartContainer::RequestHistoryData":
            HQData.RequestHistoryData(data, callback);
            break;
        case "KLineChartContainer::RequestRealtimeData":
            HQData.RequestRealtimeData(data, callback);
            break;
        case "KLineChartContainer::RequestFlowCapitalData":
            HQData.RequestFlowCapitalData(data, callback);
            break;

        case "KLineChartContainer::ReqeustHistoryMinuteData":
            HQData.RequestHistoryMinuteData(data, callback);
            break;
        case "KLineChartContainer::RequestMinuteRealtimeData":
            HQData.RequestMinuteRealtimeData(data, callback);
            break;
    }
}

HQData.RequestMinuteData = function (data, callback) {
    try {
        data.PreventDefault = true;
        var symbol = data.Request.Data.symbol;

        // Ensure symbol is a string
        if (typeof symbol !== 'string') {
            console.warn('Symbol is not a string in RequestMinuteData, converting to string');
            symbol = String(symbol);
        }

        var dayCount = data.Request.Data.daycount;
        if (!dayCount) dayCount = 1;

        console.log(`[HQData::RequestMinuteData] Symbol=${symbol}`);

        var stock = { symbol: symbol, minute: [] };
        stock.name = "Turkish Stock";
        stock.date = 20230516;
        stock.time = 1500;
        stock.yclose = 100;
        stock.price = 100;
        stock.high = 100;
        stock.low = 100;
        stock.vol = 0;
        stock.amount = 0;
        stock.minute = [];

        var hqchartData = { stock: [stock], code: 0 };

        // Initialize timer to simulate real-time data updates
        clearDing();
        initTimer(60, callback);

        callback(hqchartData);
    } catch (error) {
        console.error("Error in RequestMinuteData:", error);
        // Return empty data to prevent chart from crashing
        callback({ code: 0, stock: [] });
    }
}

HQData.CorrectMinuteData = function (minuteData, timesData) {
    var mapData = new Map();
    for (var i in minuteData) {
        var item = minuteData[i];
        mapData.set(item.time, item);
    }

    var result = [];
    for (var i in timesData) {
        var item = timesData[i];
        var value = mapData.get(item);
        if (value) {
            result.push(value);
        }
        else {
            result.push({ time: item });
        }
    }

    return result;
}

HQData.GetInternalSymbol = function (symbol) {
    var internalSymbol = {};
    internalSymbol.Symbol = symbol;
    internalSymbol.Market = 0;
    internalSymbol.Name = null;

    // Check if symbol is a string
    if (typeof symbol !== 'string') {
        console.log(`[HQData::GetInternalSymbol] Symbol is not a string: ${symbol}`);
        return internalSymbol;
    }

    var aryData = symbol.split(".");
    if (aryData.length >= 2) {
        var symbolUpper = symbol.toUpperCase();
        var market = aryData[1].toUpperCase();
        var arySymbol = aryData[0].split('_');
        var marketID = parseInt(arySymbol[1]);
        var symbolID = arySymbol[0];

        if (market == "TUR") {
            internalSymbol.Market = marketID;
            internalSymbol.Symbol = symbolID;
            internalSymbol.Name = "Turkish Stock";
        }
    }

    return internalSymbol;
}

HQData.GetMinuteApiUrl = function (symbol, dayCount) {
    var internalSymbol = HQData.GetInternalSymbol(symbol);
    if (!internalSymbol) return null;

    var url = `/api/stock/newkilne.do?stockid=${sessionStorage.getItem('stockId')}&type=PT5M`;
    return { Url: url, Symbol: symbol, InternalSymbol: internalSymbol };
}

HQData.GetKLineApiUrl = function (symbol, period, right, option) {
    var internalSymbol = HQData.GetInternalSymbol(symbol);
    if (!internalSymbol) return null;

    var internalPeriod = HQData.GetInternalPeriod(period);
    var internalRight = HQData.GetInternalRight(right);
    var url = `/api/stock/newkilne.do?stockid=${sessionStorage.getItem('stockId')}&type=${period}`;

    return { Url: url, Symbol: symbol, InternalSymbol: internalSymbol, Period: period, Right: right, internalPeriod: internalPeriod, InternalRight: internalRight };
}

HQData.GetMinuteKLineApiUrl = function (symbol, period, right, option) {
    var internalSymbol = HQData.GetInternalSymbol(symbol);
    if (!internalSymbol) return null;
    var internalPeriod = HQData.GetInternalPeriod(period);
    var internalRight = HQData.GetInternalRight(right);
    var url = `/api/stock/newkilne.do?stockid=${sessionStorage.getItem('stockId')}&type=${period}`;

    return { Url: url, Symbol: symbol, InternalSymbol: internalSymbol, Period: period, Right: right, internalPeriod: internalPeriod, InternalRight: internalRight };
}

HQData.IsShowVolChart = function (symbol) {
    return true;
}

HQData.IsEnableRight = function (period, symbol) {
    return true;
}

HQData.GetInternalPeriod = function (periodID) {
    var MAP_PERIOD = new Map(
        [
            [0, 101],   //day
            [1, 102],   //week
            [2, 103],   //month

            [3, 101],
            [4, 1],    //1min
            [5, 5],    //5min
            [6, 15],   //15min
            [7, 30],   //30min
            [8, 60],   //60min
        ]
    );

    return MAP_PERIOD.get(periodID);
}

HQData.GetInternalRight = function (right) {
    if (right == 0) return 0;
    else if (right == 1) return 1;
    else return 2;
}

HQData.RequestFlowCapitalData = function (data, callback) {
    data.PreventDefault = true;
    var hqChartData = { code: 0, stock: [] }; //如果没有数据就填空

    if (data.Self.IsDestroy == false) {
        callback(hqChartData);
    }
}

HQData.RequestHistoryData = function (data, callback) {
    data.PreventDefault = true;
    var symbol = data.Request.Data.symbol; //请求的股票代码
    var period = data.Self.Period;    //周期
    var right = data.Self.Right;      //复权

    console.log(`[HQData::RequestHistoryData] Symbol=${symbol},period= ${period}`);
    var obj = HQData.GetKLineApiUrl(symbol, period, right, null);
    obj.period = period;
    HQData.RecvHistoryData({}, callback, { Data: data, Obj: obj });
}

HQData.RecvHistoryData = function (recvData, callback, option) {
    var hqChartData = { code: 0, data: [] };
    hqChartData.symbol = option.Obj.InternalSymbol.Symbol;
    hqChartData.name = option.Obj.InternalSymbol.Symbol;
    const typeKey = option.Obj.internalPeriod;
    console.log("typeKey————————————————————————————————————", typeKey, option.Obj.period);
    getTrKline({
        stockid: sessionStorage.getItem('stockId'),
        type: option.Obj.period, //P1D PT5M
    }).then(res => {
        let resData = res.data;
        console.log("resData", resData);
        let list = [...resData];
        var yClose = list[list.length - 1][4];
        list.forEach((item, index) => {
            var today = new Date(item[0]);
            var date = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate();

            var open = parseFloat(item[1]);
            var close = parseFloat(item[2]);
            var high = parseFloat(item[3]);
            var low = parseFloat(item[4]);
            var vol = parseFloat(item[5]);
            var amount = parseFloat(item[6]);

            var newItem = [item.time, item.close, item.open, item.high, item.low, item.close,item.volume, amount];
            hqChartData.data.push(newItem);
            yClose = close;
        });
        console.log("Turkish stock K-line data______________", hqChartData);
        callback(hqChartData);
        clearDing();
        initArr = hqChartData;
        clearInterval(window.timer);
        // If it's a minute chart
        if (option.Obj.period == 3) {
            initTimer(3, callback);
        }
    });
}

HQData.RequestRealtimeData = function (data, callback) {
    data.PreventDefault = true;
    var symbol = data.Request.Data.symbol[0];     //请求的股票代码
    var period = data.Self.Period;    //周期
    var right = data.Self.Right;      //复权
    var dateRange = data.Self.ChartPaint[0].Data.GetDateRange();

    var option = { Update: true };
    if (dateRange && dateRange.End && dateRange.End.Date > 0) option.End = dateRange.End.Date;

    console.log(`[HQData::RequestRealtimeData] Symbol=${symbol}`);
    var obj = HQData.GetKLineApiUrl(symbol, period, right, option);

    $.ajax(
        {
            url: obj.Url,
            type: "GET",
            success: function (recvData) {
                HQData.RecvRealtimeData(recvData, callback, { Data: data, Obj: obj });
            }
        });
}

HQData.RecvRealtimeData = function (recvData, callback, option) {
    var data = recvData.data;
    var stock = { symbol: option.Obj.Symbol, name: data.name };

    var yClose = data.preKPrice;
    for (var i = 0; i < data.trends.length; ++i) {
        var strItem = data.trends[i];
        var item = strItem.split(',');
        var today = new Date(Date.parse(item[0]));
        var date = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate();

        var open = parseFloat(item[1]);
        var close = parseFloat(item[2]);
        var high = parseFloat(item[3]);
        var low = parseFloat(item[4]);
        var vol = parseFloat(item[5]) * 100;
        var amount = parseFloat(item[6]);

        stock.yclose = yClose;
        stock.open = open;
        stock.high = high;
        stock.low = low;
        stock.price = close;
        stock.vol = vol;
        stock.amount = amount;
        stock.date = date;

        yClose = close;
    }

    var hqchartData = { code: 0, stock: [stock] };

    if (option.Data.Self.IsDestroy == false) {
        HQData.Log("[HQData.RecvRealtimeData] hqchartData ", hqchartData);
        callback(hqchartData);
    }
}

HQData.RequestHistoryMinuteData = function (data, callback) {
    data.PreventDefault = true;
    var symbol = data.Request.Data.symbol; //请求的股票代码
    var period = data.Self.Period;    //周期
    var right = data.Self.Right;      //复权

    console.log(`[HQData::RequestHistoryMinuteData] Symbol=${symbol}`);
    var obj = HQData.GetMinuteKLineApiUrl(symbol, period, right, null);
    obj.period = period;
    HQData.RecvHistoryMinuteData({}, callback, { Data: data, Obj: obj });
}

HQData.RecvHistoryMinuteData = function (recvData, callback, option) {
    var hqChartData = { code: 0, data: [] };
    hqChartData.symbol = option.Obj.InternalSymbol.Symbol;
    hqChartData.name = option.Obj.InternalSymbol.Symbol;
    var symbol = option.Obj.InternalSymbol.Symbol;
    const typeKey = option.Obj.internalPeriod;
    const keyMap = {
        1: 'PT5M',
        5: 'PT5M',
        15: 'PT15M',
        30: 'PT30M',
        60: 'PT30M'
    };
    let today_ = new Date();

    getTrKline({
        stockid: sessionStorage.getItem('stockId'),
        type:option.Obj.period,
    }).then(res => {
        let resData = res.data;
        let list = [...resData];
        var yClose = list[list.length - 1][4];
        list.forEach((item, index) => {
            var amount = parseFloat(item[6]);
          var newItem = [item.time, item.close, item.open, item.high, item.low, item.close,item.volume, amount];
            hqChartData.data.push(newItem);
            yClose = close;
        });
        console.log("Turkish stock minute data______________", hqChartData);
        clearDing();
        initArr = hqChartData;
        callback(hqChartData);
        initTimer(typeKey * 60, callback);
    });
}

HQData.RequestMinuteRealtimeData = function (data, callback) {
    data.PreventDefault = true;
    var symbol = data.Request.Data.symbol[0];     //请求的股票代码
    var period = data.Self.Period;    //周期
    var right = data.Self.Right;      //复权
    var dateRange = data.Self.ChartPaint[0].Data.GetDateRange();

    var option = { Update: true };
    if (dateRange && dateRange.End && dateRange.End.Date > 0) option.End = dateRange.End.Date;

    console.log(`[HQData::RequestMinuteRealtimeData] Symbol=${symbol}`);
    var obj = HQData.GetMinuteKLineApiUrl(symbol, period, right, option);

    $.ajax(
        {
            url: obj.Url,
            type: "GET",
            success: function (recvData) {
                HQData.RecvMinuteRealtimeData(recvData, callback, { Data: data, Obj: obj });
            }
        });
}

HQData.RecvMinuteRealtimeData = function (recvData, callback, option) {
    var data = recvData.data;
    var hqChartData = { code: 0, data: [], ver: 2.0, symbol: option.Obj.Symbol, name: data.name }; //更新数据使用2.0版本格式

    var yClose = data.preKPrice;
    for (var i = 0; i < data.trends.length; ++i) {
        var strItem = data.trends[i];
        var item = strItem.split(',');
        var today = new Date(Date.parse(item[0]));
        var date = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate();
        var time = today.getHours() * 100 + today.getMinutes();

        var open = parseFloat(item[1]);
        var close = parseFloat(item[2]);
        var high = parseFloat(item[3]);
        var low = parseFloat(item[4]);
        var vol = parseFloat(item[5]) * 100;
        var amount = parseFloat(item[6]);

        var newItem = [date, yClose, open, high, low, close, vol, amount, time];
        hqChartData.data.push(newItem);

        yClose = close;
    }

    if (option.Data.Self.IsDestroy == false) {
        HQData.Log("[HQData.RecvMinuteRealtimeData] hqchartData ", hqChartData);
        callback(hqChartData);
    }
}

// Set up minute chart coordinate
HQData.SetMinuteChartCoordinate = function () {
    // Turkish stock trading hours (example: 10:00-18:00)
    var data =
    {
        "TUR": //Turkish stock
        {
            "name": "Turkish Stock",
            "data":
                [
                    { "Start": 1000, "End": 1800 }
                ],
            "Coordinate":
            {
                "Full":  //完整模式
                {
                    "TIME": [1000, 1030, 1100, 1130, 1200, 1230, 1300, 1330, 1400, 1430, 1500, 1530, 1600, 1630, 1700, 1730, 1800],
                    "TEXT": ["10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00"],
                    "OFFSET": 0
                },
                "Simple": //简洁模式
                {
                    "TIME": [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800],
                    "TEXT": ["10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00"],
                    "OFFSET": 0
                },
                "Min":   //最小模式
                {
                    "TIME": [1000, 1200, 1400, 1600, 1800],
                    "TEXT": ["10:00", "12:00", "14:00", "16:00", "18:00"],
                    "OFFSET": 0
                }
            }
        }
    };

    HQChart.Chart.MARKET_SUFFIX_NAME.TUR = ".tur";
    HQChart.Chart.JSChart.GetMinuteTimeStringData().TUR = data.TUR;
}

export default {
    HQData: HQData
}
